<script lang="ts" setup>
import type { SysRoleWriteParamsType } from '../utils/model'
import { formRule } from './rule'
import { getRoleDetailAPI } from '../utils/api'
import { transformI18n } from '@/plugins/i18n'
import type { MenuType } from '@/views/admin/system/menu/utils/model'

type Props = {
  id?: number
  menuPermsList: MenuType[]
}

// 表单Ref
const formRef = ref()
// props
const { id } = defineProps<Props>()
//加载状态
const loading = ref(true)
// 表单数据
const formState = ref<SysRoleWriteParamsType>({
  code: '',
  name: '',
  perms: []
})

// 判断是否是修改
if (id) {
  getDetails(id)
} else {
  loading.value = false
}

/** 获取角色详情 */
async function getDetails(id: number) {
  loading.value = true
  getRoleDetailAPI(id).then((res) => {
    let details = res.data
    Object.assign(formState.value, details)
    checkedKeys.value = details.perms
    loading.value = false
  })
}

function getRef() {
  return formRef.value
}
// 选中的key
const checkedKeys = ref<number[]>([])
// 监听选中的key
watch(checkedKeys, () => {
  formState.value.perms = checkedKeys.value
})

defineExpose({ getRef })
</script>

<template>
  <a-spin :spinning="loading">
    <a-form
      ref="formRef"
      :labelCol="{ style: { width: '80px' } }"
      :model="formState"
      :rules="formRule"
      label-align="left"
      style="margin-top: 15px"
    >
      <a-row :gutter="30">
        <a-col :span="24">
          <a-form-item label="角色名" name="name">
            <a-input v-model:value="formState.name" placeholder="请输入角色名" type="text" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="角色编号" name="code">
            <a-input v-model:value="formState.code" placeholder="请输入角色编号" type="text" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <SpDict
            v-model="formState.status"
            dictType="sys_role_status"
            label="状态"
            name="status"
            type="radio"
          />
        </a-col>
        <a-col :span="24">
          <a-form-item label="权限" name="perms">
            <a-tree
              v-model:checkedKeys="checkedKeys"
              :fieldNames="{
                children: 'children',
                title: 'name',
                key: 'id'
              }"
              :tree-data="menuPermsList"
              checkable
            >
              <template #title="{ title, key }">
                <template></template>
                <span>{{ transformI18n(title) }}</span>
              </template>
            </a-tree>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-spin>
</template>

<style scoped></style>
